{% extends "base_no_nav.html" %}

{% block title %}管理员面板 - 抽奖系统{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="text-center mb-3">
    <h2 class="text-primary mb-1">管理员面板</h2>
    <p class="text-muted small mb-0">抽奖活动管理控制台</p>
</div>

<div class="row">
    <div class="col-12 col-lg-4 mb-4">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-gamepad me-2"></i>抽奖控制</h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <h6>当前状态：
                        {% if settings.is_active %}
                            <span class="badge bg-success">抽奖进行中</span>
                        {% else %}
                            <span class="badge bg-danger">抽奖已停止</span>
                        {% endif %}
                    </h6>
                </div>

                <div class="d-grid gap-2">
                    {% if settings.is_active %}
                        <button class="btn btn-danger" onclick="toggleLottery('stop')">
                            <i class="fas fa-stop me-2"></i>停止抽奖
                        </button>
                    {% else %}
                        <button class="btn btn-success" onclick="toggleLottery('start')">
                            <i class="fas fa-play me-2"></i>开始抽奖
                        </button>
                        <button class="btn btn-warning" onclick="toggleLottery('new_round')">
                            <i class="fas fa-redo me-2"></i>开始新一轮
                        </button>
                    {% endif %}
                </div>

                <div class="mt-3">
                    <div class="progress">
                        {% set progress = (used_numbers / total_numbers * 100) | round %}
                        <div class="progress-bar" id="progressBar" role="progressbar" 
                             style="width: {{ progress }}%" 
                             aria-valuenow="{{ used_numbers }}" 
                             aria-valuemin="0" 
                             aria-valuemax="{{ total_numbers }}"
                             data-text="{{ used_numbers }}/{{ total_numbers }}">
                        </div>
                    </div>
                    <small class="text-muted">号码使用进度</small>
                </div>
            </div>
        </div>

        <div class="card shadow mt-3">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>统计信息</h5>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="border-end">
                            <h4 class="text-primary" id="participantCount">{{ results|length }}</h4>
                            <small class="text-muted">已抽奖人数</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <h4 class="text-success" id="remainingCount">{{ total_numbers - used_numbers }}</h4>
                        <small class="text-muted">剩余号码</small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-8">
        <div class="card shadow">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-trophy me-2"></i>抽奖结果</h5>
                <button class="btn btn-outline-light btn-sm" onclick="refreshResults()">
                    <i class="fas fa-sync-alt me-1"></i>刷新
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="resultsTable">
                        <thead class="table-dark">
                            <tr>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>级别</th>
                                <th>抽中号码</th>
                                <th>抽奖时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for result in results %}
                            <tr>
                                <td>{{ result.name }}</td>
                                <td>{{ result.gender }}</td>
                                <td>{{ result.level }}</td>
                                <td><span class="badge bg-primary">{{ result.lottery_number }}</span></td>
                                <td>{{ result.created_at.strftime('%H:%M:%S') }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                    {% if not results %}
                    <div class="text-center text-muted py-4">
                        <p>暂无抽奖结果</p>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 提示消息框 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="toastMessage" class="toast" role="alert">
        <div class="toast-header">
            <strong class="me-auto">系统提示</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body" id="toastBody">
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function toggleLottery(action) {
    fetch('/control-panel-2024/toggle_lottery', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({action: action})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('操作成功！');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('操作失败！', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('网络错误！', 'error');
    });
}

function refreshResults() {
    console.log('开始刷新结果...');
    fetch('/control-panel-2024/results')
    .then(response => response.json())
    .then(data => {
        console.log('收到刷新数据:', data);
        updateResultsTable(data.results);
        updateStatistics(data);
        showToast('结果已刷新');
    })
    .catch(error => {
        console.error('刷新错误:', error);
        showToast('刷新失败！', 'error');
    });
}

function updateStatistics(data) {
    console.log('更新统计信息:', data);
    
    // 更新已抽奖人数
    const participantCount = document.getElementById('participantCount');
    if (participantCount) {
        participantCount.textContent = data.results.length;
        console.log('已更新抽奖人数:', data.results.length);
    } else {
        console.error('找不到participantCount元素');
    }
    
    // 更新剩余号码
    const remainingCount = document.getElementById('remainingCount');
    if (remainingCount) {
        const remaining = data.total_numbers - data.used_numbers;
        remainingCount.textContent = remaining;
        console.log('已更新剩余号码:', remaining);
    } else {
        console.error('找不到remainingCount元素');
    }
    
    // 更新进度条
    const progressBar = document.getElementById('progressBar');
    if (progressBar) {
        const progress = Math.round((data.used_numbers / data.total_numbers) * 100);
        progressBar.style.width = progress + '%';
        progressBar.setAttribute('aria-valuenow', data.used_numbers);
        progressBar.setAttribute('data-text', `${data.used_numbers}/${data.total_numbers}`);
        console.log('已更新进度条:', progress + '%', `${data.used_numbers}/${data.total_numbers}`);
    } else {
        console.error('找不到progressBar元素');
    }
}

function updateResultsTable(results) {
    const tbody = document.querySelector('#resultsTable tbody');
    if (!tbody) {
        console.error('找不到结果表格tbody元素');
        return;
    }
    
    tbody.innerHTML = '';
    
    if (results.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无抽奖结果</td></tr>';
        return;
    }
    
    results.forEach(result => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${result.name}</td>
            <td>${result.gender}</td>
            <td>${result.level}</td>
            <td><span class="badge bg-primary">${result.lottery_number}</span></td>
            <td>${result.created_at}</td>
        `;
        tbody.appendChild(row);
    });
    
    console.log('已更新结果表格，共', results.length, '条记录');
}

function showToast(message, type = 'success') {
    // 使用全局Toast函数
    if (window.LotteryApp && window.LotteryApp.showToast) {
        window.LotteryApp.showToast(message, type);
        return;
    }
    
    // 备用方案
    alert(message);
}

// 页面加载完成后立即刷新一次
document.addEventListener('DOMContentLoaded', function() {
    console.log('管理员页面加载完成，开始初始刷新...');
    refreshResults();
});

// 自动刷新结果（每5秒）
setInterval(refreshResults, 5000);
</script>
{% endblock %}
